#!/usr/bin/perl
use CGI::Carp qw(fatalsToBrowser);
# Flatter aka Course Finder
#
##############################################################################
# Flatter                           Version 0.1.2                            #
#                                 Brian Carpenter                            #
# Created 04/2001                Last Modified 04/07/2003                    #
#                                 http://flatter.sourceforge.net             #
##############################################################################
# COPYRIGHT NOTICE                                                           #
# Copyright 2001        Brian Carpenter  All Rights Reserved.                #
#                                                                            #
# FlatSearch may be used and modified free of charge by anyone so long as    #
# this copyright notice and the comments above remain intact.  By using this #
# code you agree to indemnify Brian Carpenter from any liability that        #
# might arise from its use.                                                  #
#                                                                            #
# Selling the code for this program without prior written consent is         #
# expressly forbidden.  In other words, please ask first before you try and  #
# make money off of my program.                                              #
#                                                                            #
# Obtain permission before redistributing this software over the Internet or #
# in any other medium.  In all cases copyright and header must remain intact #
##############################################################################



###############
#Variables    #
###############
&GetCwd(); # Finds the current directory script is in and 
		   # saves it in $vars{base_dir}

$global_config_file="flatter.cfg"; 
&read_config();

$filename = $vars{file1}; #default value could be changed via input
$semester = $vars{filetitle1};
@fields = split(',',$vars{fields1});
$vars{index}=$vars{index1};

#############
#Initialize #
#############
&ParseForm();
#decide which flatfile to use via hidden field in form
if ($form{f} eq "$vars{filecode1}") {$filename = $vars{file1};
									 $semester = "$vars{filetitle1}";
									 @fields = split(',',$vars{fields1});
									 $vars{index}=$vars{index1};
									 }

if ($form{f} eq "$vars{filecode2}") {$filename = $vars{file2};
									 $semester = "$vars{filetitle2}";
									 @fields = split(',',$vars{fields2});
									 $vars{index}=$vars{index2};
									}

$semforcookie = "$form{f}"; #tells cookie.pl what file to use.

open(DATA,"<$filename") or die "Can not open Database";
@db = <DATA>;           #throw file into array
close(DATA);

foreach $item (@db)   #gets rid of EOL characters
   {
           chomp($item);
           if($item ne "") { push(@newdb,$item); }
   }
@db = @newdb;



($vars{field1},$vars{field2},$vars{field3},$vars{field4},$vars{field5},$vars{field6},$vars{field7},$vars{field8},$vars{field9},$vars{field10} ) = @fields;


#form variables given scalar names
$field1frm = $form{field1};
$field2frm = $form{field2};
$field3frm = $form{field3};
$field4frm = $form{field4};
$field5frm = $form{field5};
$field6frm = $form{field6};
$field7frm = $form{field7};
$field8frm = $form{field8};
$field9frm = $form{field9};
$field10frm = $form{field10};

$found = 0;             #counter for how many record matches

$hit = 0;               #counter for how many pattern matches per record

$varcount = 0;          #Form variable counter

# count how many variables we are using
if ($field1frm ne "none" && $field1frm ne "") {$varcount++;}
if ($field2frm ne "none" && $field2frm ne "") {$varcount++;}
if ($field3frm ne "none" && $field3frm ne "") {$varcount++;}
if ($field4frm ne "none" && $field4frm ne "") {$varcount++;}
if ($field5frm ne "none" && $field5frm ne "") {$varcount++;}
if ($field6frm ne "none" && $field6frm ne "") {$varcount++;}
if ($field7frm ne "none" && $field7frm ne "") {$varcount++;}
if ($field8frm ne "none" && $field8frm ne "") {$varcount++;}
if ($field9frm ne "none" && $field9frm ne "") {$varcount++;}
if ($field10frm ne "none" && $field10frm ne "") {$varcount++;}

##########################
#Start of Search Engine  #
##########################
foreach $record (@db){            #check each record in database file
     &checkrecord($record);
    }



#################
#Build Output   #
#################
$fontsize = "<font size=\"$vars{font}\">"; #change these to change the fontsize of
$endfont = "</font>";             #the output

print "content-type:text/html\n\n";
print ApplyTemplate("$vars{header}");
print "<table cellspacing=\"3\" cellpadding=\"1\" align \"center\" width=\"100%\">";
print "<tr><td colspan=\"12\"><center><h2>$semester</h2></center></td></tr>";
print "<tr><td colspan=\"12\">Found : $found </td></tr>";
print "<tr><td>$fontsize $vars{field1} $endfont</td><td>$fontsize $vars{field2} $endfont</td><td>$fontsize $vars{field3} $endfont</td><td>$fontsize $vars{field4} $endfont</td><td>$fontsize $vars{field5} $endfont</td><td>$fontsize $vars{field6} $endfont</td><td>$fontsize $vars{field7} $endfont</td><td>$fontsize $vars{field8} $endfont</td><td>$fontsize $vars{field9} $endfont</td><td>$fontsize $vars{field10} $endfont</td><td>$fontsize Add to Cart $endfont</td></tr>";

    foreach $match(@matches)
    {
    ($f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$f10) = split(/\,/,$match);
    	if ($vars{index} eq "0"){ $indexer=0;}
    	if ($vars{index} eq "1"){ $indexer=$f1;}
    	if ($vars{index} eq "2"){ $indexer=$f2;}
    	if ($vars{index} eq "3"){ $indexer=$f3;}
    	if ($vars{index} eq "4"){ $indexer=$f4;}
    	if ($vars{index} eq "5"){ $indexer=$f5;}
    	if ($vars{index} eq "6"){ $indexer=$f6;}
    	if ($vars{index} eq "7"){ $indexer=$f7;}
    	if ($vars{index} eq "8"){ $indexer=$f8;}
    	if ($vars{index} eq "9"){ $indexer=$f9;} 
    	if ($vars{index} eq "10"){$indexer=$f10;}
    print  "<tr><td>$fontsize $f1 $endfont</td><td>$fontsize $f2 $endfont</td><td>$fontsize $f3 $endfont</td><td>$fontsize $f4 $endfont</td><td>$fontsize $f5 $endfont</td><td>$fontsize $f6 $endfont</td><td>$fontsize $f7 $endfont</td><td>$fontsize $f8 $endfont</td><td>$fontsize $f9 $endfont</td><td>$fontsize $f10 $endfont</td><td>";
    if ($indexer){
    print "<a href=\"$vars{cookieurl}?action=1&data=$indexer&sem=$semforcookie\" target=\"_Blank\">$fontsize Add $fontend</a> </td>";
    }
    print "</td></tr>";
    }
print "</table>";   

print ApplyTemplate("$vars{footer}");


sub checkrecord
{
    my($reccheck) = @_;
    ($f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$f10) = split(/\,/,$reccheck);

    if ($field1frm ne "none" && $field1frm ne "")              #skip if user left blank
        {
        if ($f1 =~ /$field1frm/i) { $hit++; }   #if variable match add
        }                                               # to hit
    if ($field2frm ne "none" && $field2frm ne "")
        {
        if ($f2 =~ /$field2frm/i) { $hit++; }         #continues checking rest
        }                                               #of variables
    if ($field3frm ne "none" && $field3frm ne "")
        {
        if ($f3 =~ /$field3frm/i) { $hit++; }
        }
	if ($field4frm ne "none" && $field4frm ne "")
        {
        if ($f4 =~ /$field4frm/i) { $hit++; }
        }
    if ($field5frm ne "none" && $field5frm ne "")
        {
        if ($f5 =~ /$field5frm/i) { $hit++; }

        }
    if ($field6frm ne "none" && $field6frm ne "")
        {
        if ($f6 =~ /$field6frm/i) { $hit++; }

        }
    if ($field7frm ne "none" && $field7frm ne "")
        {
        if ($f7 =~ /$field7frm/i) { $hit++; }

        }        
    if ($field8frm ne "none" && $field8frm ne "")
        {
        if ($f8 =~ /$field8frm/i) { $hit++; }

        }
    if ($field9frm ne "none" && $field9frm ne "")
        {
        if ($f9 =~ /$field9frm/i) { $hit++; }

        }        
    if ($field10frm ne "none" && $field10frm ne "")
        {
        if ($f10 =~ /$field10frm/i) { $hit++; }

        }        
    if ($hit >= $varcount)          #if variable matches are more or equal to
        {                           #number of variables
        push(@matches,$reccheck);   #add record to matches array
        $found++;                   #add matches counter
        }
    $hit = 0;                       #reset for next record
}

sub ApplyTemplate {
local(*FILE);         # filehandle
local($file);         # file path
local($HTML);         # HTML data

$file = $_[0] || die "Template : No template file specified\n";

open(FILE, "<$file") or die "Template : Couldn't open $file : $!\n";
while (<FILE>) { $HTML .= $_; }
close(FILE);

$HTML =~ s/\$(\w+)/${$1}/g;

return $HTML;
}

sub read_config {
	my $config_file;
	$vars{config} = "$global_config_file";
	$config_file = $vars{base_dir} . $vars{config};
	my $key,$val;
	open(IN,$config_file) || die ("Can't open config file $config_file.");
	while(<IN>) {
		next if /^#/;
		chomp;
		($key,$val) = ( /([^=]+)=(.*)/ );
		$key = lc($key);
		$val =~ s|\[(\S+)\]|$vars{$1}|g;
		$val =~ s|\s*$||;
		$vars{$key} = $val;
		}
	close(IN);
}

sub GetCwd {
	if ($base_dir) { $vars{base_dir} = $base_dir; }
	return if $vars{base_dir};
	my $path =  $ENV{'PATH_TRANSLATED'} || $ENV{'SCRIPT_FILENAME'};
	unless ($path) {
		die("Your server does not provide the PATH_TRANSLATED or SCRIPT_FILENAME environment variables.<br><br>Please see the installation documentation for how to set the \$base_dir variable manually.");
		exit(0);
		}
	$path =~ s|[^/\\]*$||;
	$vars{base_dir} = $path;
	}
	

sub ParseForm {
$query = $ENV{QUERY_STRING};
if ($query =~ /\w+/)
{
    @pairs = split ('&',$query); #check for url sumbitted info
}                                # like cgi-bin/coursefinder.pl?time=pm&sem=fall
else
{
read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
@pairs = split(/&/, $buffer);
}

foreach $pair (@pairs)
{
   ($name, $value) = split(/=/, $pair);
   $value =~ tr/+/ /;
   $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
   $value =~ s/\n//g;
   $value =~ s/\r/<BR>/g;
   $form{$name} = $value;
}
}
